import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'taro-axios';
import Taro from '@tarojs/taro';
import Storage from '@/utils/storage';
import storage from '@/utils/storage';

const instance = axios.create({
  // 超时时间 1 分钟
  timeout: 30 * 1000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

interface RequestConfig extends AxiosRequestConfig {
  isTransformResponse?: boolean;
}

instance.interceptors.request.use(
  async (config: AxiosRequestConfig) => {
    const token = await Storage.getItem('token');
    config.headers = {
      Authorization: `Bearer ${token}`,
      token,
      ...config.headers,
    };
    return config;
  },
  (err: AxiosError) => {
    Promise.reject(err);
  }
);
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    return response;
  },
  (err: AxiosError) => {
    return Promise.reject(err);
  }
);

const showToast = (title: string) => {
  Taro.showToast({
    title,
    icon: 'none',
    duration: 3000,
  });
};
const showMessage = (title: unknown) => {
  const message = JSON.stringify(title).replace(/"/g, '');
  if (message.indexOf('Network') > -1) {
    showToast('请求失败，请联系客服');
  } else if (message.indexOf('timeout') > -1) {
    showToast('请求超时');
  } else {
    showToast(message);
  }
};
// Taro.showToast 和loading 是单例 所以只有成功时候hideLoading 其他情况showToast
export default function request<T>(options: RequestConfig = {}) {
  // Taro.showLoading({
  //   title: '加载中...',
  // });
  Taro.showNavigationBarLoading();
  return new Promise<T>((resolve, reject) => {
    instance(options)
      .then((response: AxiosResponse) => {
        if (options.isTransformResponse) {
          resolve(response.data);
        } else if (response?.status === 200 && response?.data?.code === 0) {
          resolve(response.data.data);
          // Taro.hideLoading();
        } else {
          throw response;
        }
      })
      .catch((result) => {
        if (result?.status === 200 && result?.data?.code === 103) {
          Taro.navigateTo({
            url: '/pages/login/index',
          });
          // 清楚本地缓存
          storage.removeItem('token');
        } else {
          // 其他情况 code 非 0 情况 有message 就显示
          showMessage(result?.data?.message ?? result?.message);
        }
        reject(result);
      })
      .finally(() => {
        Taro.hideNavigationBarLoading();
      });
  });
}
